/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSumClosest = function(nums,target) {
    nums.sort((v1,v2)=>v1-v2);
    if(nums.length<3)return [];
    //console.log(nums);

    let dis = 99999999;
    let result = null;

    let length = nums.length;
    for(let i=0;i<length-2;i++){

        let j = i+1;
        let k = length-1;

        while(j<k){
            let sum = nums[i]+nums[j]+nums[k];
            //console.log(j,k,sum);
            if(sum>target){
                let tmp_dis = Math.abs(sum-target);
                if(dis>tmp_dis){
                    dis =  tmp_dis;
                    result = sum;
                }
                k--;
            }
            else if(sum<target){
                let tmp_dis = Math.abs(sum-target);
                if(dis>tmp_dis){
                    dis =  tmp_dis;
                    result = sum;
                }
                j++;
            }
            else{
                return target;
            }
        }
    }
    return result;
};



console.log(threeSumClosest([1,2,4,8,16,32,64,128],82));